package com.qf.web.controller;

import com.qf.domain.Goods;
import com.qf.domain.PageBean;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * projectName:myxiaomi
 * author:LiPengChong
 * time:2024/4/16 20:59
 * description:
 */
@WebServlet("/goodsservlet")
@MultipartConfig(maxFileSize = 5*1024*1024,maxRequestSize = 20*1024*1024)
public class GoodsServlet extends BaseServlet {

    //【分页查询】
    //http://localhost:8080/goodsservlet?method=getGoodsListByTypeId&typeId=1
    public String getGoodsListByTypeId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取前端数据
        //商品类别
        String typeId = request.getParameter("typeId");
        //商品名称
        String goodsName = request.getParameter("goodsName");
        //商品页面
        String pageNum = request.getParameter("pageNum");
        //页大小
        String pageSize = request.getParameter("pageSize");
        //2.校验
        int page_num = 1;
        int page_size = 8;//设置一个每页数据量，8
        try {
            if (!StringUtils.isEmpty(pageNum)) {
                page_num = Integer.parseInt(pageNum);//若获取的pageNum不为空，将字符串型的pageNum转为整型赋值给page_num
                if (page_num < 1) {
                    page_num = 1;
                }
            }
            if (!StringUtils.isEmpty(pageSize)) {
                page_size = Integer.parseInt(pageSize);//原理同上
                if (page_size < 1) {
                    page_size = 8;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //封装条件
        StringBuilder where = new StringBuilder("where 1=1 ");
        List<Object> params = new ArrayList<>();
        if (!StringUtils.isEmpty(typeId)) {
            where.append(" and typeid=? ");
            params.add(typeId);
        }
        if (!StringUtils.isEmpty(goodsName)) {
            where.append(" and name like ? ");
            params.add("%" + goodsName + "%");
        }
        //如果没有条件---查询所有
        if (params.size() <= 0) {
            return "/goodsList.jsp";
        }
        try {
            //调用业务逻辑
            GoodsService goodsService = new GoodsServiceImpl();
            PageBean<Goods> pageBean = goodsService.findByPage(page_num, page_size, where.toString(), params);
            System.out.println("pageBean:" + pageBean);//没有数据 后台问题
            //存下来这三个做数据回写
            request.setAttribute("typeId", typeId);
            request.setAttribute("goodsName", goodsName);
            request.setAttribute("pageBean", pageBean);
            //成功的话转发到商品详情页
            return "/goodsList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        //失败了就重定向到index页面
        return "redirect:/index.jsp";
    }

    //【通过ID找商品信息】
    // http://localhost:8080/goodsservlet?method=getGoodsById&id=1
    public String getGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String id = request.getParameter("id");//商品id
        System.out.println("商品的id：" + id);
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "商品id不能为空");
            return "redirect:/message.jsp";
        }
        try {
            //调用业务逻辑
            GoodsService goodsService = new GoodsServiceImpl();
            Goods goods = goodsService.findById(Integer.parseInt(id));
            //转发重定向
            request.setAttribute("goods", goods);
            return "/goodsDetail.jsp";

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询失败" + e.getMessage());
            return "redirect:/message.jsp";
        }
    }


    /*---------------------------------------------------------后台商品模块--------------------------------------------------------------------------------*/
    //【后台添加商品】
    //goodsservlet?method=addGoods
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断管理员是否登录

        //2.获取前端数据
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        //获取图片
        Part picture = request.getPart("picture");
        //非空验证
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "商品名称不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(typeid)) {
            request.setAttribute("msg", "商品类型不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(pubdate)) {
            request.setAttribute("msg", "商品上架时间不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(price)) {
            request.setAttribute("msg", "商品价格不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(star)) {
            request.setAttribute("msg", "商品评分不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(intro)) {
            request.setAttribute("msg", "商品简介不能为空");
            return "/admin/addGoods.jsp";
        }
        //3.调用业务逻辑
        int type_id = Integer.parseInt(typeid);
        if (type_id < 0) {
            request.setAttribute("msg", "请选择合适的商品类型");
            return "/admin/addGoods.jsp";
        }
        //处理图片
        //【优化】：IE浏览器上传路径问题 (不处理的话IE浏览器上的路径是绝对路径，只要相对路径即可不需要绝对路径)
        String dis = picture.getHeader("Content-Disposition");
        System.out.println("项目目录" + dis);
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);//substring、lastIndexOf上面有解释
        System.out.println("截取路经：" + filename);
        filename = filename.substring(filename.indexOf("\\") + 1);//找到最后一次出现\的位置并截取。例如:E:\QF\11.jpg 就能找到11.jpg
        System.out.println("截取后的文件名：" + filename);

        String uuidFileName = null;
        if (!filename.equals("")) {//文件名不为空上传图片
            //保存图片
            String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "imags");//File.separator是用来分隔文件路径的系统相关的分隔符
            File dir = new File(basePath);
            if (!dir.exists()) {
                dir.mkdirs();//目录不存在则创建目录
            }
            //获取后缀名(如：jsp,png等)
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            uuidFileName = UUID.randomUUID().toString().replace(("-"), "");
            uuidFileName = uuidFileName + "." + ext;//和获取的后缀名连接起来，形成一个新的文件名
            picture.write(basePath + File.separator + uuidFileName);//将上传的图片文件写入到指定路径下
            picture.delete();//清除缓存
            System.out.println("保存图片成功");
            try {
                //3.1调用业务层代码
                GoodsService goodsService = new GoodsServiceImpl();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Goods goods = new Goods(0, name, sdf.parse(pubdate), uuidFileName, new BigDecimal(price), Integer.parseInt(star), intro, type_id);
                goodsService.add(goods);
                response.getWriter().write("<script>alert('添加成功');window.location='admin/addGoods.jsp';</script>");
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("<script>alert('添加失败');window.location='admin/addGoods.jsp';</script>");
            }
        }
        return null;
    }


    //【后台查看商品】
    //goodsservlet?method=getGoodsList
    public String getGoodsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String name = request.getParameter("name");
        String pubdate = request.getParameter("pubdate");
        //2.多条件查询
        //2.1.创建可变长字符串where，创建存放参数的集合params
        StringBuilder where = new StringBuilder("");
        List<Object> params = new ArrayList<>();
        //2.2追加个sql语句
        where.append(" where 1=1 ");
        //3.非空验证
        if (!StringUtils.isEmpty(name)) {
            where.append("and name like ? ");
            params.add("%" + name + "%");
        }
        if (!StringUtils.isEmpty(pubdate)) {
            where.append("and pubdate=? ");
            params.add(pubdate);
        }
        try {
            //4.调用业务逻辑
            GoodsService goodsService = new GoodsServiceImpl();
            List<Goods> goodsList = goodsService.adminFind(where, params);
            request.setAttribute("goodsList", goodsList);
            return "/admin/showGoods.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查看失败");
            return "/message.jsp";
        }
    }

    //【后台删除商品】
    //goodsservlet?method=deleteGoods
    public String deleteGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String id = request.getParameter("id");
        //2.非空验证
        if (StringUtils.isEmpty(id)) {
            return "/admin/showGoods.jsp";
        }
        try {
            //3.调用业务逻辑
            GoodsService goodsService = new GoodsServiceImpl();
            goodsService.adminDeleteGoods(Integer.parseInt(id));
            //转发、重定向
            return "redirect:/goodsservlet?method=getGoodsList";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('删除失败');window.location.href='admin/showGoods.jsp';</script>");
        }
        return null;
    }

    //【后台更新商品】
    //goodsservlet?method=updateById
    public String updateById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String id = request.getParameter("id");
        //2.非空验证
        if (StringUtils.isEmpty(id)){
            return "/admin/showGoods.jsp";
        }
        //3.调用业务逻辑
//        GoodsService goodsService = new GoodsServiceImpl();
//        Goods goods = goodsService.adminUpdateById(Integer.parseInt(id));
//        request.setAttribute();
        return null;
    }
}